#include "Cell.h"
#include "../Managers/GameManager.h"
#include "../Renderer/DeferredRenderer.h"
#include "../GameObjects/GameObject.h"

Cell::Cell(const Vec3f &pos, float slope)
	: pos(pos), pos2d((int)pos.x(), (int)pos.z())
{
	if(pos2d.x() == -65 && pos2d.y() == 2)
		int hello = 0;

	TerrainId type;
	if(pos.y() < -1.0f)
		type = TERRAIN_DEEP_WATER;
	else if(pos.y() < 0.0f)
		type = TERRAIN_SHALLOW_WATER;
	else if(pos.y() < 5.0f)
		type = TERRAIN_SAND;
	else if(pos.y() < 40.0f && abs(slope) < 0.4f)
		type = TERRAIN_GRASS_LUSH;
	else if(pos.y() < 100.0f && abs(slope) < 0.4f)
		type = TERRAIN_GRASS_NORMAL;
	else if(pos.y() < 150.0f && abs(slope) < 0.4f)
		type = TERRAIN_GRASS_SPARSE;
	else if(pos.y() >= 150.0f && abs(slope) < 0.4f)
		type = TERRAIN_SNOW_DEEP;
	else if(pos.y() < 140.0f && abs(slope) < 0.5f)
		type = TERRAIN_GROUND;
	else if(pos.y() <= 160.0f && abs(slope) < 0.5f)
		type = TERRAIN_GROUND_FROZEN;
	else if(pos.y() > 160.0f && abs(slope) < 0.1f)
		type = TERRAIN_SNOW_NORMAL;
	else if(pos.y() > 160.0f && abs(slope) < 0.5f)
		type = TERRAIN_SNOW_SHALLOW;
	else if(abs(slope) >= 0.5f)
		type = TERRAIN_ROCK_BARE;
	else
		type = TERRAIN_ROCK_DIRTY;

	terrainType = GameManager::getSingleton()->getTerrainTypeMgr()->getTerrainType(type);
	walkable = terrainType->walkable;
}

Cell::~Cell()
{
}

void Cell::render()
{
	auto g_buffer = GameManager::getSingleton()->getRenderer();

	//Define ground graphics for this cell
	g_buffer->addSymbol(pos2d, terrainType->frgr_symbol, 0.0f, false);

	//Foreground shading
	g_buffer->shade(pos2d, terrainType->frgr_color_f,	DeferredRenderer::RL_FOREGROUND, DeferredRenderer::RT_DIFFUSE);
	g_buffer->shade(pos2d, Vec3f(0.5f, 0.5f, 0.5f),		DeferredRenderer::RL_FOREGROUND, DeferredRenderer::RT_SPECULAR);

	//Background shading
	g_buffer->shade(pos2d, terrainType->bkgr_color_f,	DeferredRenderer::RL_BACKGROUND, DeferredRenderer::RT_DIFFUSE);
	g_buffer->shade(pos2d, Vec3f(0.5f, 0.5f, 0.5f),		DeferredRenderer::RL_BACKGROUND, DeferredRenderer::RT_SPECULAR);
	g_buffer->shade(pos2d, Vec3f(0.0f, 1.0f, 0.0f),		DeferredRenderer::RL_BACKGROUND, DeferredRenderer::RT_NORMAL);
	g_buffer->shade(pos2d, pos.y(),														 DeferredRenderer::RT_DEPTH);
	g_buffer->shade(pos2d, 0.5f,														 DeferredRenderer::RT_SHININESS);

	//FOV info
	g_buffer->setMapInfo(pos2d, true, walkable);

	for(auto gameObject : gameObjects)
		gameObject->render();
}
